package com.woniu113.junk.commons.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 根据键取出一个字符串数据
     */
    public String get(String key) throws Exception{
        return stringRedisTemplate.opsForValue().get(key);
    }
    /**
     * 保存一个字符串键值对数据,提供两种重载:有过期时间和无过期时间
     */
    public void set(String key,String value) throws Exception{
        stringRedisTemplate.opsForValue().set(key,value);
    }
    public void set(String key,String value,long time) throws Exception{
        stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);//键\值\过期时间\时间单位(以秒为单位)
    }
    //判断Key是否存在
    public Boolean exists(String key)throws Exception{
        return stringRedisTemplate.hasKey(key);
    }
    //自增+1
    public void increment(String key)throws Exception{
        stringRedisTemplate.opsForValue().increment(key);
    }

    //删除Key
    public void delete(String key)throws Exception{
        stringRedisTemplate.delete(key);
    }
}
